package com.itheima.reggie.controller;

import com.itheima.reggie.common.OssClient;
import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private OssClient ossClient;

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();//1.jpg
        int index = originalFilename.lastIndexOf(".");//  1
        String suffix = originalFilename.substring(index);//.jpg
        //随机生成图片的名字  gutrwaestygiutrawstgiuhiset
        String fileName = UUID.randomUUID().toString().replace("-","")+suffix;
        //按日期生成文件夹
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");//2022/12/12
        String formatDate = dateFormat.format(new Date());//2022/12/12

        fileName = formatDate+"/"+fileName;
        String url = ossClient.transferToAliyunOss(fileName, file.getInputStream());

        return R.success(url);//https://chengdu-reggie-62-huige.oss-cn-chengdu.aliyuncs.com/exampledir/exampleobject.txt
    }
    /*
        文件下载
     *//*
    @GetMapping("/download")
    public void upload(String name, HttpServletResponse response) throws IOException {
        //获取文件的输入流
        FileInputStream fileInputStream = new FileInputStream(baseUrl + name);
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");

        byte[] bytes = new byte[1024];
        int len;
        while ((len =fileInputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        fileInputStream.close();
    }*/
}
